package com.example.demo.service;

import com.example.demo.mapper.ProductMapper;
import com.example.demo.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.Optional;

@Service
public class ProductService {

    @Autowired
    private ProductMapper productMapper;

    private final ObjectMapper objectMapper = new ObjectMapper();

    // 根据产品ID获取产品信息，返回Optional<Product>对象
    public Optional<Product> getProductById(Long id) {
        return Optional.ofNullable(productMapper.findById(id));
    }

    // 获取所有产品信息
    public List<Product> getAllProducts() {
        return productMapper.findAll();
    }

    // 获取产品图片URL数组
    public String[] getProductImages(Long id) {
        Optional<Product> product = getProductById(id);
        if (product.isPresent()) {
            Product productData = product.get();
            String imagesJson = productData.getImages();
            try {
                // 解析 JSON 数组
                return objectMapper.readValue(imagesJson, String[].class);
            } catch (Exception e) {
                e.printStackTrace();
                return new String[]{};
            }
        }
        return new String[]{};
    }

    // 根据分类名称获取产品
    public List<Product> getProductsByCategoryName(String categoryName) {
        return productMapper.findByCategoryName(categoryName);
    }

    // 保存产品
    public void saveProduct(Product product) {
        productMapper.save(product);
    }

    // 更新产品
    public void updateProduct(Product product) {
        productMapper.update(product);
    }

    // 删除产品
    public void deleteProduct(Long id) {
        productMapper.delete(id);
    }
}
